/** @jsxImportSource @emotion/react */
import * as React from "react";
import {DdMenu,  DdMenuItem} from "../DropdownMenu";
import {ToastContainer, useToast} from "../Toast";
import {MainMenuBar, PanelEnlargeCtx, useMMenuBarOcup} from "../MainMenuBar";
import {MenuDivider, MenuItem, MenuList} from "../Menu";
import {Button,  buttonReset} from "../Button";
import {
    IconActivity,
    IconArrowLeft,
    IconArrowRight, IconArrowUpRight,
    IconChevronDown, IconChevronUp,
    IconKey, IconMapPin, IconMoreHorizontal,
    IconMoreVertical,
    IconPackage,
    IconUser
} from "../Icons";
import {
    Collapse,
    CommitInput,
    Input,
    InputLine, TabPanel,
    Text,
    useCollapse,
    useTheme,
    VerticalMenu
} from "../../src";
import {TwoHalfFrame } from "../TwoHalfFrame";
import {  Global } from "@emotion/react";
import {TwoHalfRightPanel} from "../TwoHalfRightPanel";
import {IconButton, IconRefButton} from "../IconButton";
// import {PanInfo} from "framer-motion";
import {a, useSpring, useSprings, animated} from "@react-spring/web";
import type {Meta, StoryObj} from "@storybook/react";
import {fn} from "@storybook/test";
import {CommonPager, UnitList} from "./TwoHalfCarousel.stories";

const meta: Meta<typeof TwoHalfFrame> = {
    title: 'Example/TwoHalfFrame',
    component: TwoHalfFrame,
    parameters: {
        layout: 'centered',
    },
    tags: ['autodocs'],
    argTypes: {
    },
    args: { onClick: fn() },
};
export default meta;
type Story = StoryObj<typeof TwoHalfFrame>;
export const Basic: Story = {
    decorators: [
        (Story) => (
            <>
                <BasicTest />
            </>
        ),
    ],
};
export const 框架不好测试: Story = {
    decorators: [
        (Story) => (
            <>
                <NestedPage> <PagerCommon/> </NestedPage>
            </>
        ),
    ],
};

function BasicTest() {
    //页面路由器头上面的部分
    const [enlarge, setEnlarge] = React.useState(null);
    //上面这句和底下的<PanelEnlargeCtx.Provider  value={{ enlarge, setEnlarge }}>正常应该出现在页面路由器入口组件上的。
    const theme = useTheme();
    const toast = useToast();
    //第1层次的两半页面轮播台控制
    const [activecas, setActivecas] = React.useState(0);
    const [activeTab, setActiveTab] = React.useState( 0);
    const [cod, setCod] = React.useState<string|undefined>('vU2');
    const [repNo, setRepNo] = React.useState<string|undefined>('');
    const [show, setShow] = React.useState(false);
    const eos =useCollapse(show,false);
    //【修改】独立<LeftPanelChanging/>两个半边页面状态变量不能交叉！   //另外半边右边的 ；报错！useMemo里面不允许函数体当中再嵌套useState;
    const rightPanel = React.useMemo(() => {
        //不能放这里：  const [show, setShow] = React.useState(true);
        return  <LeftPanelChanging/>;
    }, []);
    //StoryBook内嵌的 iframe当中，问题！ 被插入div， 高度被裁减。
    return (
        <PanelEnlargeCtx.Provider  value={{ enlarge, setEnlarge,  setActivecas }}>

            <Global
                styles={{
                    html: {
                        overflowX: 'hidden',
                        [theme.mediaQueries.md]: {
                            backgroundAttachment: "fixed",
                            backgroundSize: "cover",
                        },
                        padding: 'unset',
                    },
                    body:{
                        padding: '0 !important',
                    }
                }}
            />
            <MainMenuBar  css={{
                justifyContent: "space-between",
                "@media print": {
                    display: 'none',
                }
            }}
            >
                <DdMenu label="菜单"  divStyle={ {
                    lineHeight: '1.0',
                } as any }
                >
                    <DdMenuItem label="Undo2" />
                    <DdMenuItem label="Redo3" />
                    <DdMenuItem label="Cut" disabled />
                    <DdMenu label="Copy as">
                        <DdMenuItem label="Text" />
                        <DdMenuItem label="Video" />
                        <DdMenu label="Image">
                            <DdMenuItem label=".png" />
                            <DdMenuItem label="是电风扇"
                                        onClick={ (e) => {
                                            toast({title: "提交一个3链接"});
                                        } }
                            />
                            <DdMenuItem label=".svg" />
                            <DdMenuItem label=".gif" />
                        </DdMenu>
                        <DdMenuItem label="Audio" />
                    </DdMenu>
                    <DdMenu label="Share">
                        <DdMenuItem label="Mail" />
                        <DdMenuItem label="Instagram" />
                    </DdMenu>
                </DdMenu>
                <Button
                    size="xs"
                    intent="primary"
                    iconBefore={<IconArrowRight />}
                    onPress={() => {  }}
                >
                    搜索
                </Button>
                <Button
                    size="xs"
                    intent="primary"
                    iconBefore={
                        <img
                            css={{
                                marginRight: theme.spaces.sm,
                                width: "25px",
                                height: "25px"
                            }}
                            src={''} alt={''}
                            aria-hidden
                        />
                    }
                    onPress={() => { } }
                >
                    待办
                </Button>
                <Button
                    size="xs" noBind
                    intent="primary"
                    iconBefore={<IconKey />}
                >
                    任务
                </Button>
            </MainMenuBar>

            <TwoHalfFrame  rightPanel={rightPanel} >
                <div  style={ {
                    display: 'flex',
                    alignItems: 'center',
                    flexDirection: 'column',
                }  }>
                    <h5>Floating UI Dropdo wn Menu三事大夫UI Dropdown Menu三事大安达完了了翁另外市543多夫</h5>

                    <Text variant="h3"
                          className="ListItem__primary"
                          wrap={true}
                          css={{ display: "block", fontWeight: 500 }}
                    >
                        Floating UI Dropdo wn Menu三事大安达<p/>完了了翁另外市543多夫
                    </Text>
                    <InputLine label={`立刻变动编号:`}>
                        <Input type='text'  value={ repNo || ''}
                               readOnly={false}  onChange={e => setRepNo( e.currentTarget.value||undefined ) } />
                    </InputLine>
                    <InputLine label={`单位内部编号:`}>
                        <CommitInput autoFocus={true}  value={ cod || ''}  onSave={txt => setCod(txt||undefined) } />
                    </InputLine>
                    <Button
                        variant="ghost"
                        intent="primary"
                        iconAfter={eos.show  ? <IconChevronUp /> : <IconChevronDown />}
                        {...eos.buttonProps}
                        css={{whiteSpace:'unset'}}
                    >
                        {<Text variant="h5" css={{color: eos.show ? theme.colors.palette.red.base:undefined}}>测试Collapse刻下guai</Text>}
                    </Button>
                    <Collapse {...eos.collapseProps}  noAnimated={false}>
                        shemta弹出可看的..<p/>.玩法师的
                        <div css={{textAlign: 'right',padding:'0.2rem'}}>
                            <Button
                                variant="ghost"
                                intent="primary"
                                iconAfter={eos.show  ? <IconChevronUp /> : <IconChevronDown />}
                                {...eos.buttonProps}
                            >
                                确认收起
                            </Button>
                        </div>
                    </Collapse>

                </div>
            </TwoHalfFrame>

            <ToastContainer />
        </PanelEnlargeCtx.Provider>
    )
}

interface Props {
    children?: React.ReactNode;
}
/*
TwoHalfFrame左右两边必须独立，需要确保左边页面的编辑器修改导致render不应该立刻引起右边页面的立刻变动。
* */
const LeftPanelChanging: React.FC<Props> =
({
     ...props
 }) => {
    const theme = useTheme();
    const toast = useToast();
    const [show, setShow] = React.useState(true);
    return (
        <TwoHalfRightPanel
            title={  `关联的检验信息 wn Menu三事大安达`
            }
            back={
                <IconButton  noBind  icon={<IconArrowLeft />}
                             variant="ghost"
                             label="后退"
                             size="md"
                             css={{
                                 marginRight: theme.spaces.sm,
                                 [theme.mediaQueries.md]: {
                                     display: "none"
                                 }
                             }}
                />
            }
            menu={
                <VerticalMenu>
                    <DdMenuItem label="Ro">
                        SFSD  <IconMoreVertical />
                    </DdMenuItem>
                    <DdMenuItem label="奇怪了"/>
                    <DdMenuItem label="事发地" onClick={(e) => {
                        toast({
                            duration: 99500,
                            title: "Hello world",
                            subtitle: "Excepteur exercitation 停留 2500 ms.afas四惠大少时诵诗书所厦大沙东",
                            //position: "top-right"
                            intent: 'error',
                        });
                    }}> <IconMoreVertical />
                    </DdMenuItem>
                    <DdMenuItem label="事地"  >
                        <div   css={{
                            display: 'inline-flex',
                            flexDirection: 'column',
                            flexWrap: 'wrap',
                            alignItems: 'center',
                            maxWidth: '9rem',
                            lineHeight: '1.1',
                        }} >sdfadf闪电发货手动滑稽是动画都或多或少35胜多负少都会
                        </div>
                    </DdMenuItem>
                    <DdMenuItem disabled label="Rzdo"   onPress={(e) => {
                        console.log("外部的7c7sa习性-")
                    }}
                    >Cut<IconMoreVertical />
                    </DdMenuItem>
                    <DdMenu
                        label="Copy as">
                        <DdMenuItem label="Text"/>
                        <DdMenuItem label="Video"/>
                        <DdMenu label="Image">
                            <DdMenuItem label=".png"/>
                            <DdMenuItem label="风扇Show"
                                        onClick={(e) => {
                                            setShow(!show);
                                            toast({
                                                render: ({ onClose, id }) => {return "show修改了！";}
                                            });
                                        }}/>
                            <DdMenuItem label=".svg"/>
                            <DdMenuItem label=".gif"/>
                        </DdMenu>
                        <DdMenuItem label="Audio"/>
                    </DdMenu>
                    <DdMenu label="Share">
                        <DdMenuItem label="Mail"/>
                        <DdMenuItem label="Instagram"/>
                    </DdMenu>
                </VerticalMenu>
            }
        >
            <h3>ARIA Authoring Practices show当前是={show? '真':'假'}, Guide</h3>
            <div css={{ padding: "1rem" }}>

                <MenuList>
                    <MenuItem contentBefore={<IconPackage />}
                              onPress={async () => {
                                  await toast({title: "提交一个网页链接"});
                              } }
                    >
                        提交审核
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem
                        contentBefore={<IconUser />}
                        onPress={() => alert("Hello 1")}
                    >
                        Drink coffee
                    </MenuItem>
                    <MenuItem contentBefore={<IconPackage />}>Eat pancakes</MenuItem>
                    <MenuDivider />
                    <MenuItem contentBefore={<IconMapPin />}>Make pizza</MenuItem>
                    <MenuItem contentBefore={<IconActivity />}>
                        Dance {show? '真':'假'} out
                    </MenuItem>
                    <MenuItem contentBefore={<IconArrowUpRight />}>
                        Anything you ask
                    </MenuItem>
                </MenuList>

            </div>

        </TwoHalfRightPanel>
    );
};


interface NestedPageProps {
    children?: React.ReactNode;
}
const NestedPage: React.FunctionComponent<NestedPageProps> = ({children} )=> {
    const [enlarge, setEnlarge] = React.useState(null);
    const theme = useTheme();
    const toast = useToast();
    //第1层次的两半页面轮播台控制
    const [activecas, setActivecas] = React.useState(0);
    const [activeTab, setActiveTab] = React.useState( 0);
    const rightPanel=(
        <TwoHalfRightPanel
            title={  `关联的检验信息 wn Menu三事大安达`
            }
            back={
                <IconButton  noBind  icon={<IconArrowLeft />}
                             variant="ghost"
                             label="后退"
                             size="md"
                             css={{
                                 marginRight: theme.spaces.sm,
                                 [theme.mediaQueries.md]: {
                                     display: "none"
                                 }
                             }}
                />
            }
            menu={
                <VerticalMenu>
                    <DdMenuItem label="Ro">
                        SFSD  <IconMoreVertical />
                    </DdMenuItem>
                </VerticalMenu>
            }
        >

            <h3>ARIA Authoring Practices Guide</h3>
            <div css={{ padding: "1rem" }}>
            </div>
            <a
                target="_blank"
                href="https://www.w3.org/WAI/ARIA/apg/patterns/menubutton/"
                rel="noreferrer"
            >
                Menu Button
            </a>
        </TwoHalfRightPanel>
    );

    return (
        <PanelEnlargeCtx.Provider  value={{ enlarge, setEnlarge,  setActivecas }}>

            <Global
                styles={{
                    html: {
                        overflowX: 'hidden',
                        [theme.mediaQueries.md]: {
                            backgroundAttachment: "fixed",
                            backgroundSize: "cover",
                        },
                        padding: 'unset',
                    },
                    body:{
                        padding: '0 !important',
                    }
                }}
            />
            <MainMenuBar  css={{
                justifyContent: "space-between",
                "@media print": {
                    display: 'none',
                }
            }}
            >
                <Button
                    size="xs"
                    intent="primary"
                    iconBefore={<IconArrowRight />}
                    onPress={() => {  }}
                >
                    搜索
                </Button>
                <Button
                    size="xs"
                    intent="primary"
                    iconBefore={
                        <img
                            css={{
                                marginRight: theme.spaces.sm,
                                width: "25px",
                                height: "25px"
                            }}
                            src={''} alt={''}
                            aria-hidden
                        />
                    }
                    onPress={() => { } }
                >
                    待办
                </Button>
                <Button
                    size="xs" noBind
                    intent="primary"
                    iconBefore={<IconKey />}
                >
                    任务
                </Button>
            </MainMenuBar>

            <TwoHalfFrame  rightPanel={rightPanel}
            >
                <div  style={ {
                    display: 'flex',
                    alignItems: 'center',
                }  }>
                    <h5>Floating UI Dropdo wn Menu三事大夫UI Dropdown Menu三事大安达完了了翁另外市543多夫</h5>
                </div>
                <h3>Floating UI Dropdo wn Menu三事大安达完了了翁另外市543多夫</h3>

                {children}

            </TwoHalfFrame>
            <ToastContainer />
        </PanelEnlargeCtx.Provider>
    );
}

//专用Pager测试修改版本， 内部的Stack也是测试修改版本
const PagerCommon: React.FunctionComponent<UnitMainProps> = props => {
    const [activeTab, setActiveTab] = React.useState(0);
    const { enlarge, setEnlarge,setActivecas,getActivecas} =useContext(PanelEnlargeCtx);
    function onChildCannotDrag2(e: Event, dragProps: PanInfo) {
        const { offset } = dragProps
        if (offset.x > 0) {
            setActivecas(getActivecas!()===1? 0 : 1);
        } else if (offset.x < 0) {
            setActivecas(getActivecas!()===1? 0 : 1);
        }
    }
    //返回true=脱离控制，交给下一层次的的Pager控制
    const onChildCannotDrag = React.useCallback(([x, y]:Vector2) => {
        if (x < 0 || x > 0) {
            setActivecas(getActivecas!()===1? 0 : 1);
            return true;
        }
        return false;
    }, [setActivecas, getActivecas]);


    const ref = React.useRef()

    const [color, setColor] = React.useState('black')
    const toggleColor = () => setColor((c) => (c === 'black' ? '#ec625c' : 'black'))

    const [style, api] = useSpring(() => ({ scale: 1, x: 0, y: 0 }))
    const [styleOuter, apiOuter] = useSpring(() => ({ x: 0, y: 0 }))
    const [coords, set] = React.useState({ x: 0, y: 0 })


    // @ts-ignore
    const bind = useDrag(
        (state) => {
            //这里intentional感觉不准确，过滤掉太多了，舍弃掉intentional状态变量。
            const {offset: [x, y] , active, movement: [mx,my], direction: [xDir,yDir] , cancel,
                swipe:[swpx,], last,  canceled,tap, event,intentional } = state;
            event.stopPropagation()    //去掉看
            //   if (intentional) {
            // let [x, y] = state[gesture]
            // set({ x, y })
            //
            // if (pointerOptions.lock) {
            //     const dx = window.innerWidth / 2 - 40
            //     const dy = window.innerHeight / 2 - 40
            //     x = ((x + Math.sign(x) * dx) % window.innerWidth) - Math.sign(x) * dx
            //     y = ((y + Math.sign(y) * dy) % window.innerHeight) - Math.sign(y) * dy
            // }
            api.start({
                // scale: active ? 1.2 : 1,
                x,
                y,
                // immediate: pointerOptions.lock
            })
            //  }
        },
        {
        }
    )

    return (
        <CommonPager  lazyLoad={false}  noBind={false}
                      value={activeTab}   onRequestChange={i => setActiveTab(i)}
                      onNestDragEnd={onChildCannotDrag}
                      css={{
                          height: '100%',
                      }}
        >
            <TabPanel id="company"
                      css={{
                          // height: '100%',
                      }}
            >
                <UnitList add={'公司'}/>
            </TabPanel>
            <TabPanel id="person"
                      css={{
                          // height: '100%',
                      }}
            >
                <UnitList add={'个人'}/>
            </TabPanel>
        </CommonPager>
    );
}

